﻿using Microsoft.Extensions.Logging;
using SingleBlog.Core.Data;
using SingleBlog.Core.Services;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;

namespace SingleBlog.Framework.Logger
{
    using Framework;
    using Microsoft.AspNetCore.Identity;

    public class BlogLogger<TCategoryName> : ILogger<TCategoryName>
    {
        private readonly IServiceProvider _serviceProvider;
        private TCategoryName _categoryName;
        private Func<LogLevel, bool> _filter;
        public BlogLogger(TCategoryName categoryName, IServiceProvider serviceProvider,Func<LogLevel,bool> filter=default(Func<LogLevel,bool>))
        {
            _serviceProvider = serviceProvider;
            _categoryName = categoryName;
            _filter = filter;

            if (_filter == null)
            {
                _filter = m => m >= LogLevel.Error;
            }
        }


        public IDisposable BeginScope<TState>(TState state) => null;
        public bool IsEnabled(LogLevel logLevel)
        {
            return _filter(logLevel);
        }
        public async void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            var message = formatter(state, exception);

            if (exception != null)
            {
               message= message.Append(Environment.NewLine, Environment.NewLine, exception.ToString());
            }
            try
            {
                var messageSender = _serviceProvider.GetService<IMessageSender>();
                var settingService = _serviceProvider.GetRequiredService<SettingService>();
                var user = await _serviceProvider.GetRequiredService<UserManager<SingleBlogUser>>().FindByIdAsync("1");

                var generateSetting = settingService.GetGeneralSetting();

                var body = $@"亲爱的{user.UserName}，以下是站点根据配置发送的日志报告：<br/>
{new String('-', 100)}<br/>
<p>
{message}
</p>

<br/>
您的站点：{generateSetting.SiteName}<br/>
你的站点地址：<a href='{{0}}' target='_blank'>{{0}}</a>
".StringFormat(generateSetting.SiteUrl);

                await messageSender.SendAsync(new MailMessage($"[{generateSetting.SiteName}]异常日志", body, user.Email));
            }
            catch(Exception ex)
            {

            }
        }
    }
}
